package com.zhang.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhang.common.lang.Const;
import com.zhang.common.lang.Result;
import com.zhang.entity.Files;
import com.zhang.service.FilesService;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 张立松
 * @since 2023-04-27
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    FilesService filesService;

    //博客编辑中上传图片文件
    @RequiresAuthentication
    @PostMapping("/upload")
    public Result uploadImg(@RequestParam("file") MultipartFile file) throws IOException {

        String fileMd5 = SecureUtil.md5(file.getInputStream()); //计算文件md5与数据库进行比对
        Files dbFiles = filesService.getOne(new QueryWrapper<Files>().eq("md5", fileMd5));
        if(dbFiles != null){     //该文件存在则直接返回URL
            return Result.success(dbFiles.getUrl());
        }

        //该文件不存在则上传到服务器文件系统
        String uuid = IdUtil.fastSimpleUUID();
        String type = FileUtil.extName(file.getOriginalFilename());
        String fileName = uuid + "." + type;
        String filePath = Const.Default_Files_FilePath+"/"+fileName;
        File upFile = new File(filePath);
        file.transferTo(upFile);

        //上传后将信息存到数据库
        Files upFiles = new Files();
        upFiles.setCreated(LocalDateTime.now());
        upFiles.setMd5(fileMd5);
        upFiles.setName(fileName);
        upFiles.setType(type);
        upFiles.setSize(file.getSize());
        upFiles.setUrl(Const.Base_Url+"/file/get/"+fileName);
        filesService.save(upFiles);

        return Result.success(upFiles.getUrl());
    }

    @GetMapping("/get/{fileName}")
    public void getFile(@PathVariable("fileName") String fileName, HttpServletResponse response) {

        try{
            File file = new File(Const.Default_Files_FilePath + "/" + fileName);
            FileInputStream fileInputStream = new FileInputStream(file);
            ServletOutputStream servletOutputStream = response.getOutputStream();

            byte[] bytes = new byte[1024];
            int len;
            while ((len=fileInputStream.read(bytes))!=-1){
                servletOutputStream.write(bytes,0,len);
                servletOutputStream.flush();
            }
            fileInputStream.close();
            servletOutputStream.close();
        }catch (Exception e){
            System.out.println("FileController----找不到指定文件");
        }

    }

}

